package com.aaa.marketresearch.dataresource.dao;

import com.aaa.marketresearch.dataresource.domain.Bill;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * @author Nail
 */
@Repository
public class BillDAOImpl implements BillDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public List<Bill> getAll() {
        List<Bill> result = em.createQuery("FROM Bill b").getResultList();
        return result;
    }

    @Override
    public Bill getById(Integer id) {
        final String query = "FROM Bill b WHERE b.id=:id";
        Object obj = em.createQuery(query).setParameter("id", id).getSingleResult();
        if (obj != null) {
            return (Bill)obj;
        } else {
            return null;
        }
    }

    @Override
    public void save(Bill bill) {
        this.em.merge(bill);
    }

    @Override
    public boolean delete(Integer id) {
        final String query = "DELETE Bill b WHERE b.id = :id";
        int count = em.createQuery(query).setParameter("id", id).executeUpdate();
        return (count > 0);
    }
}
